# -*- coding: utf-8 -*-
# 将redis中的图书信息，保存到MySQL中
import redis
import pymysql
import json

def main():
    # redis数据库信息
    rediscli=redis.StrictRedis(host='localhost', port=6379, db=0)
    # mysql数据库信息
    db=pymysql.connect(host='localhost',user='root',password='',db="douban",charset="utf8")
    cursor=db.cursor()
    count=0

    while True:
        source, data = rediscli.blpop(["book:items"])
        try:
            item=json.loads(data)
            # 图书信息转化为字典格式
            d=dict(item)
            keys=",".join(d.keys())
            values=",".join(['%s']*len(d))
            sql="insert into book (%s) values (%s)" % (keys,values)
            cursor.execute(sql,tuple(d.values()))
            db.commit()
            count+=1
            print("写入成功",d["id"],count)
        except Exception as err:
            db.rollback()
            print("SQL执行错误，原因：",err)
            print(d)


if __name__ == '__main__':
    main()

    # import re
    # strs='<span>'\
    #   '<span class="pl"> 译者</span>:'\
    #         '<a class="" href="/search/%E9%99%88%E8%8B%B1">陈英</a>'\
    # '</span><br/>'
    # print(strs)
    # price=re.search('<span.*?>\s*译者.*?</span>(.*?)<br.*?>',strs,re.S | re.I)
    # print(price)
